package shopping.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import redis.clients.jedis.Jedis;
import shopping.dao.impl.CategoryDaoMysql;
import shopping.domain.Category;
import shopping.dao.CategoryDao;
import shopping.exceptions.CategoryHasProductException;
import shopping.service.CategoryService;
import shopping.utils.BeanFactory;
import shopping.utils.RedisUtil;

import java.util.List;

public class CategoryServiceImpl implements CategoryService {
    private CategoryDao categoryDao = BeanFactory.newInstance(CategoryDao.class);
    public List<Category> findAll() {
        //使用Redis添加缓存
        //1. 连接Redis
        Jedis connection = null;
        //使用finally进行释放连接
        try {
            connection = RedisUtil.getConnection();

            //先查询缓存,第一次查询肯定是没有的
            String categories = connection.get("categories");
            if(categories == null){
                //如果没有缓存，调用Dao查询数据库，并同时添加一份到缓存中
                System.out.println("该数据不在缓存中");
                List<Category> all = categoryDao.findAll();
                //存一份到缓存中
                String s = new ObjectMapper().writeValueAsString(all);
                connection.set("categories",s);

                return all;
            }else{
                //如果有缓存，直接返回缓存中数据
                List list = new ObjectMapper().readValue(categories, List.class);
                return list;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            if (connection != null) connection.close();
        }
    }

    public Category findById(String cid) {
        return new CategoryDaoMysql().findById(cid);
    }

    @Override
    public void save(Category category) {
        categoryDao.save(category);

        //刷新缓存
        refresh();
    }

    @Override
    public void update(Category category) {
        categoryDao.update(category);
        refresh();
    }

    /**
     * 删除分类方法
     * @param cid   分类id
     * @throws CategoryHasProductException  自定义异常
     */
    @Override
    public void del(String cid) throws CategoryHasProductException {
        //提前查询数据库，判断从表是否存在数据，如果有数据就不允许删除。
        int count = categoryDao.countByCid(cid);
        //判断是否存在数据
        if(count > 0){
            //大于0 存在数据，抛异常告诉Servlet
            throw new CategoryHasProductException();
        }else{
            //不存在数据，可以删除
            categoryDao.del(cid);
            refresh();
        }
    }

    private void refresh() {
        //连接redis
        Jedis connection = null;
        try {
            connection = RedisUtil.getConnection();

            try {
                List<Category> list = categoryDao.findAll();
                String s = new ObjectMapper().writeValueAsString(list);
                connection.set("categories",s);
            } catch (JsonProcessingException e) {

            }
        }finally {
            connection.close();
        }
    }
}
